#!/usr/local/bin/bash
# 
# Compresses .log files in Siebel logarchvie folder.
#
# Description: Should be executed from logarchive dir.
# Script is capable to handle hundreds of thousands files in single dir.
# It traverses all archive_xxx, backups existing .tar.gz file if there
# could be a conflict, tars all .log files, gzips resulting tar and
# finally removes all original .log files.
# Ensure enough disk space for the resulting tar file.
#  
#	History:
#	0.1	2012-04-19 romans.krjukovs@gmail.com
#		Initial version.
#
TARGET='*.log'
OUTPUT=archive_`date +"%Y-%m-%d"`.tar
for i in `find . -type d -name 'archive*'`; do
	cd $i 
	echo -n "In `pwd`: "

	COUNT=`find . -name "$TARGET" -type f|wc -l`
	if [ $COUNT != 0 ]; then
 		echo "$COUNT .log files found for compressing.."

		if [ -f $OUTPUT.gz ]; then
			echo " backing up existing $OUTPUT.gz.."
 			mv $OUTPUT.gz $OUTPUT.gz.`date +"%Y-%m-%d"`
	 	else
 			echo " no .tar.gz found - OK"
		fi

		if [ ! -f $OUTPUT ]; then 
			echo -n " creating new empty tar file.."
 			touch dummy && tar cf $OUTPUT dummy && rm dummy 
	 		echo `ls -la "$OUTPUT"`
 		else
 			echo " appending to existing .tar file - "`ls -la "$OUTPUT"`
		fi
		
		echo "Compressing files now.."
		time ((find . -name '*.log' -type f | xargs -t tar uf $OUTPUT) && gzip $OUTPUT && (find . -name '*.log' -type f -exec rm '{}' \;))

	else
 		echo "No .log files found for compressing"
	fi
	cd ..
done